package com.boang.controller;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.StringUtils;
import com.boang.entity.po.SysRole;
import com.boang.service.SysRoleService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.net.URLEncoder;
import java.util.ArrayList;

@Controller
@RequestMapping("/excel")
public class ExcelExportController {

    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("/export/roles")
    public void exportUserList(HttpServletResponse response) throws IOException {
        // 1. 准备数据（实际应从数据库获取）
        List<SysRole> dataList = sysRoleService.list();

        // 2. 设置响应头
        String fileName = URLEncoder.encode("角色列表", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 3. 写入Excel
        EasyExcel.write(response.getOutputStream(), SysRole.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("角色数据")
                .doWrite(dataList);
    }

    @PostMapping("/import/roles")
    public String importUsers(@RequestParam("file") MultipartFile file) throws IOException {
        List<SysRole> successList = new ArrayList<>();
        // 1. 创建监听器
        AnalysisEventListener<SysRole> listener = new AnalysisEventListener<SysRole>() {
            @Override
            public void invoke(SysRole data, AnalysisContext context) {
                successList.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 批量保存成功数据
                sysRoleService.saveBatch(successList);
            }
        };

        // 2. 读取Excel
        EasyExcel.read(file.getInputStream(), SysRole.class, listener)
                .sheet()
                .doRead();

        return "导入完成，成功：" + successList.size() + "条";
    }
}